package com.hotau.member;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.InputFilter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.hotau.Executable;
import com.hotau.HotauActivity;
import com.hotau.HotauConstants;
import com.hotau.R;
import com.hotau.util.DialogUtil;
import com.hotau.util.HttpRequestAsynTask;
import com.hotau.util.HttpUtil;
import com.hotau.util.ValidateUtils;

/**
 * 找回失去的账号密码
 * @author liujia (liujia9234@126.com)
 * @data 2011-12-9
 * @version 1.0
 * <ul>
 * 		<li>1.0 创建</li>
 * </ul>
 */
public class LostPwdFragment extends Fragment implements OnClickListener {
    public static final int MAX_PASSWORD_LENGTH = 20;
	public static final String TAG = "LostPwdFragment";
	public static final int LOST_VERIFY_PWD_SUBMIT = 1;
	public static final int LOST_GET_CHECKCODE_WAIT = 2;
	
	private EditText lost_et_usercode = null;
	private EditText lost_et_phone_checkcode = null;
	private EditText lost_et_password = null;
	private EditText lost_et_verify_password = null;
	private Button lost_btn_checkcode_resend = null;
	private Button lost_btn_submit = null;
	public String guid = "";
	public String loginName = null;
	
	/**
	 * 异步请求Task
	 */
	HttpRequestAsynTask lost_pwd_code_task = null; //获取找回密码校验码
	HttpRequestAsynTask lost_pwd_check_code = null;//验证校验码
	HttpRequestAsynTask lost_pwd_submit_task = null;//确认找回密码
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		initAllWidget();
		initAllEvent();
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		loginName = getArguments().getString("loginName");
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.member_lost_pwd, container,false);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.member_lost_btn_checkcode_resend:
			if(!ValidateUtils.isTelePhone(lost_et_usercode.getText().toString())){
				DialogUtil.showDialog(getActivity(),"", "请输入手机号码或者手机号码不合法");
				return;
			}
			StringBuffer sb = new StringBuffer();
			sb.append("Form:userCode="+lost_et_usercode.getText().toString());
			sb.append(";terminalCode=" + HotauConstants.getTerminalCode(getActivity()));
			sb.append(";type=2");
			//获取找回密码校验码返回处理
			lost_pwd_code_task = new HttpRequestAsynTask(getActivity()){
				@Override
				protected void doPostExecute(String result) {
					// TODO Auto-generated method stub
					Log.d(TAG, "lost_check_code_response :" + result);
					try {
						JSONObject data = new JSONObject(result);
						if(data != null && data.getInt("result") == 1){
							//成功验证码成功
							//lost_et_phone_checkcode.setText(data.getString("checkCode"));
							lost_btn_checkcode_resend.setBackgroundResource(R.drawable.member_lost_pwd_btn_wait_bg);
							lost_btn_checkcode_resend.setEnabled(false);
							guid = data.getString("guid");
							new Thread(new Runnable() {
								@Override
								public void run() {
									// TODO Auto-generated method stub
									int i = 61;
									while (i > 0) {
										Message msg = new Message();
										msg.what = LOST_GET_CHECKCODE_WAIT;
										msg.getData().putString("text",
												(--i) + "秒后重发");
										lostHander.sendMessage(msg);
										if (i == 1) {
											lostHander.postDelayed(new Runnable() {
												@Override
												public void run() {
													lost_btn_checkcode_resend.setText("");
													lost_btn_checkcode_resend.setBackgroundResource(R.drawable.member_lost_pwd_btn_bg);
													lost_btn_checkcode_resend.setEnabled(true);
												}
											}, 1000);
											break;
										}
										try {
											Thread.sleep(1000);
										} catch (InterruptedException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
								}
							}).start();
							
						}else{
							//失败
							DialogUtil.showDialog(getActivity(), "", data.getString("errorMsg"));
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						DialogUtil.showDialog(getActivity(), "", "获取校验码数据出错");
					}
				}
			};
			lost_pwd_code_task.execute(HotauConstants.MEMBER_GET_CHECK_CODE_URL,sb.toString(),HttpUtil.UTF8_ENCODING);
			Log.d(TAG, "lost_check_code_request :" + sb.toString());
			break;
		case R.id.member_lost_btn_submit:
			//验证
			if(!ValidateUtils.isTelephone(lost_et_usercode.getText().toString())){
				DialogUtil.showDialog(getActivity(), "", "手机号码不合法");
				return;
			}
			if("".equals(guid.trim())){
				DialogUtil.showDialog(getActivity(), "", "验证码不存在或已经失效,请重新获取");
				return;
			}
			if("".equals(lost_et_phone_checkcode.getText().toString().trim())){
				DialogUtil.showDialog(getActivity(), "", "请输入验证码");
				return;
			}
			if( !(lost_et_password.getText().length() >=8 && lost_et_password.getText().length() <= 20)){
				DialogUtil.showDialog(getActivity(), "", "密码必须是8-20个字符");
				return;
			}
			if( !(lost_et_verify_password.getText().length()>=8 && lost_et_verify_password.getText().length()<= 20)){
				DialogUtil.showDialog(getActivity(), "", "确认密码必须是8-20个字符");
				return;
			}
			
			if( !lost_et_password.getText().toString().equals(lost_et_verify_password.getText().toString())){
				DialogUtil.showDialog(getActivity(), "", "两次输入密码不一致");
				return;
			}
			//验证校验码
			StringBuilder sb_submit = new StringBuilder();
			sb_submit.append("Form:userCode="+lost_et_usercode.getText());
			sb_submit.append(";guid="+guid);
			sb_submit.append(";checkCode="+lost_et_phone_checkcode.getText());
			sb_submit.append(";terminalCode=" + HotauConstants.getTerminalCode(getActivity()));
			sb_submit.append(";type="+2);
			
			//重置登录密码(resetLoginPassword)
			StringBuilder sb_verify_submit = new StringBuilder();
			sb_verify_submit.append("Form:userCode="+lost_et_usercode.getText());
			sb_verify_submit.append(";newPwd="+lost_et_password.getText());
			sb_verify_submit.append(";confirmPwd="+lost_et_verify_password.getText());
			sb_verify_submit.append(";terminalCode=" + HotauConstants.getTerminalCode(getActivity()));
			
			lost_pwd_check_code = new HttpRequestAsynTask(getActivity()){
				HotauActivity csmbpActivity = (HotauActivity) getActivity();
				
				@Override
				protected String doInBackground(String... params) {
					// TODO Auto-generated method stub
					String result = HttpUtil.doWrapedHttp(csmbpActivity, params[0],params[1],params[2]);
					try {
						JSONObject data = new JSONObject(result);
						if(data != null && data.getInt("result") == 1){
//							lostHander.sendEmptyMessage(LOST_VERIFY_PWD_SUBMIT);
							return  HttpUtil.doWrapedHttp(csmbpActivity, params[3],params[4],params[5]);
						}else{
							//失败
							//DialogUtil.showDialog(csmbpActivity, "", data.getString("errorMsg"));
							return "#__#"+result;
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						//DialogUtil.showDialog(csmbpActivity, "", "效验码验证返回数据错误");
					}
					return "";
				}

				@Override
				protected void doPostExecute(String result) {
					
					if(result.indexOf("#__#")!=-1){
						JSONObject data;
						try {
							data = new JSONObject(result.replace("#__#", ""));
							DialogUtil.showDialog(csmbpActivity, "", data.getString("errorMsg"));
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
					}else{
						Log.d(TAG, "lost_verify_submit_response :" + result.toString());
						try {
							JSONObject data = new JSONObject(result);
							if(data != null && data.getInt("result") == 1){
								//修改密码成功
								DialogUtil.showDialog(csmbpActivity, "", "找回密码成功",new Executable() {
									@Override
									public void execute() {
										// TODO Auto-generated method stub
										csmbpActivity.popFragment();
									}
								});
							}else{
								//失败
//								csmbpActivity.pushFragment("信息提示", new MessagePromptFragment(false,data.getString("errorMsg")));
								DialogUtil.showDialog(csmbpActivity, "", data.getString("errorMsg"));
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			};
			
			
			lost_pwd_check_code.execute(HotauConstants.MEMBER_VALIDATE_CHECK_CODE_URL,sb_submit.toString(),HttpUtil.UTF8_ENCODING,HotauConstants.MEMBER_RESET_LOGIN_PWD_URL,sb_verify_submit.toString(),HttpUtil.UTF8_ENCODING);
			
			Log.d(TAG, "lost_check_code_validate_request :" + sb_submit.toString());
			break;
		
		default:
			break;
		}
	}
	
	/**
	 * 初始化所有控件
	 */
	public void initAllWidget() {
		lost_et_usercode = (EditText) getActivity().findViewById(R.id.member_lost_et_usercode);
		
		Log.i("mytag", "找回登陆密码----------->" + loginName);
		if(loginName != null 
				&& !loginName.equals("")
					&& ValidateUtils.isMobile(loginName)) {
			lost_et_usercode.setEnabled(false);
			lost_et_usercode.setText(loginName);
		}
		
		lost_et_phone_checkcode = (EditText) getActivity().findViewById(R.id.member_lost_et_phone_checkcode);
		lost_et_password = (EditText) getActivity().findViewById(R.id.member_lost_et_password);
		lost_et_verify_password = (EditText) getActivity().findViewById(R.id.member_lost_et_verify_password);
		lost_btn_checkcode_resend = (Button) getActivity().findViewById(R.id.member_lost_btn_checkcode_resend);
		lost_btn_submit = (Button) getActivity().findViewById(R.id.member_lost_btn_submit);
		lost_et_password.setFilters(new InputFilter[]{new InputFilter.LengthFilter(MAX_PASSWORD_LENGTH)});  

	}
	
	/**
	 * 初始化所有事件
	 */
	public void initAllEvent() {
		lost_btn_checkcode_resend.setOnClickListener(this);
		lost_btn_submit.setOnClickListener(this);
	}
	
	//消息处理Hander
	public Handler lostHander = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case LOST_VERIFY_PWD_SUBMIT:
				//重置登录密码(resetLoginPassword)
				StringBuilder sb_verify_submit = new StringBuilder();
				sb_verify_submit.append("Form:userCode="+lost_et_usercode.getText());
				sb_verify_submit.append(";newPwd="+lost_et_password.getText());
				sb_verify_submit.append(";confirmPwd="+lost_et_verify_password.getText());
				sb_verify_submit.append(";terminalCode=" + HotauConstants.getTerminalCode(getActivity()));
				//提交登录密码
				lost_pwd_submit_task = new HttpRequestAsynTask(getActivity()){
					HotauActivity csmbpActivity = (HotauActivity) getActivity();
					@Override
					protected void doPostExecute(String result) {
						// TODO Auto-generated method stub
						Log.d(TAG, "lost_verify_submit_response :" + result.toString());
						try {
							JSONObject data = new JSONObject(result);
							if(data != null && data.getInt("result") == 1){
								//修改密码成功
//								csmbpActivity.pushFragment("信息提示", new MessagePromptFragment(true,"找回密码成功"));
								DialogUtil.showDialog(csmbpActivity, "", data.getString("errorMsg"));
								DialogUtil.showDialog(csmbpActivity, "", data.getString("errorMsg"), new Executable() {
									@Override
									public void execute() {
										// TODO Auto-generated method stub
										csmbpActivity.pushFragment("登录",new LoginFragment());
									}
								} );
							}else{
								//失败
								//csmbpActivity.pushFragment("信息提示", new MessagePromptFragment(false,data.getString("errorMsg")));
								DialogUtil.showDialog(csmbpActivity, "", data.getString("errorMsg"));
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
					}
					
				};
				
				lost_pwd_submit_task.execute(HotauConstants.MEMBER_RESET_LOGIN_PWD_URL,sb_verify_submit.toString(),HttpUtil.UTF8_ENCODING);
				Log.d(TAG, "lost_verify_submit_request :" + sb_verify_submit.toString());
				break;
			case LOST_GET_CHECKCODE_WAIT:
				String text = msg.getData().getString("text");
				lost_btn_checkcode_resend.setText(text);
				break;
			default:
				break;
			}
			
		}
	};

}
